Java Programming Language
Java Classes and Objects Exercises

These exercises are designed to evaluate your knowledge, comprehension, application and analysis of the Java structure statement syntax – specifically related to classes and objects. It is expected that you should be able to correctly answer all or nearly all of the questions and problems presented. You should do these exercises by yourself.

1. What is difference between a class and an object in Java?

 

 

2. What does it mean that an object variable has a value of null?

 

 

3. Identify declaration type, valid and invalid Java syntax for class, constructor, method & property declarations. If the syntax is invalid explain why. Some items may have multiple types and parts of the code valid and others invalid, indicate each.

Java syntax

Declaration Type Valid/Invalid

Why Invalid?

public Car() { }

   

void getColor()

{ return color; }

   

public class Car

{

String color;

public CreateCar(String p1)

{

color = p1;

}

public Car() { }

}

   

public int getNumSeats()

{

return 4;

}

   

 

4. Identify valid and invalid Java syntax for object creation, method & property usage. If the syntax is invalid explain why.

Assume a class named Car that has a property named model and created with a color String. Also, assume a class Point that has a method called getX and is created with two integer values.

Java syntax

Valid/Invalid

Why Invalid?

String s = "Hello There";

   

Point p = (1,2);

   

model = c.model;

   

Car c = new Car("black");

   

p.getX();

   

slen = s.length;

   

 

5. Explain what happens on each line of the following Java code.

/*
Assume Point is an object that takes two integers as arguments and they represent coordinate points on a graph. It also has a method to get the X and get the Y coordinates.  These are getX() and getY() respectively. There is an equals(Point p1) method that compares the X & Y coordinates of an object with the object argument passed in the method.
There is a clone(Point p1) method that copies the X & Y coordinates of an object with the object argument passed in the method.
*/

public class TestPoint
{

void doSomething(Point point)
{
q = point;
}

Point p;
Point q;

p = new Point(2, 5);
q = p;
if (p==q)
{
 System.out.println(q.getX());
 System.out.println(q.getY());
}

q = new Point(12, 14);
p = q;
p = new Point(3, 7);
System.out.println(q.getX());
System.out.println(q.getY());
System.out.println(p.getX());
System.out.println(p.getY());

if (p==q)
{
 System.out.println(p.getX());
 System.out.println(p.getY());
}

q = new Point(3, 7);
if (p==q)
{
 System.out.println(p.getX());
 System.out.println(p.getY());
}
if (p.equals(q))
{
 System.out.println(p.getX());
 System.out.println(p.getY());
}

p = new Point(9, 8);
doSomething(p);
System.out.println(q.getX());
System.out.println(q.getY());
p.clone(q);
System.out.println(p.getX());
System.out.println(p.getY());

}